﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Syndication;
using System.Xml;
using System.Reflection;

namespace TerrariViewer
{
    class UpdateChecker
    {
        public enum ReleaseStatus
        {
            Stable = 1,
            Beta = 2,
            Alpha = 4
        }

        public enum UpdateFilter
        {
            Stable = ReleaseStatus.Stable,
            Beta = Stable | ReleaseStatus.Beta,
            Alpha = Beta | ReleaseStatus.Alpha
        }

        public string CheckForUpdates(string feedUrl, UpdateFilter filter)
        {
            
            var currentVersion = Assembly.GetExecutingAssembly().GetName().Version;
            var reader = XmlReader.Create(feedUrl);
            var formatter = new Atom10FeedFormatter();
            
            try
            {
                formatter.ReadFrom(reader);
            }
            catch
            {
                return "No Updates Available";
            }
            


            var update = formatter.Feed.Items.Where(i =>
                {
                    Version version;
                    var versionParsed = Version.TryParse(i.Title.Text, out version);

                    return versionParsed &&
                        version > currentVersion &&
                        i.Categories.Any(c => ((int)Enum.Parse(typeof(UpdateFilter), c.Name, true)) != 0);
                }).OrderByDescending(i => i.LastUpdatedTime).FirstOrDefault();


            if (update != null)
            {
                return update.Links.Single().Uri.ToString();
            }
            else
            {
                return "No Updates Available";
            }


        }
    }
}
